package com.lwq.fast.log.fastlogcore.client.redis;

import cn.hutool.core.util.StrUtil;
import com.lwq.fast.log.fastlogcore.client.AbstractClient;
import com.lwq.fast.log.fastlogcore.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 *
 * @author 刘文强
 */
public class RedisClient extends AbstractClient {



    private static RedisClient instance;

    private JedisPool jedisPool;

    /**
     * redis host
     */
    private String host;
    /**
     * redis port
     */
    private int port;
    /**
     * redis 认证密码
     */
    private String auth;


    /**
     * 连接超时时间
     */
    private int timeOut=5000;
    /**
     * 最小空闲数  空闲数依据访问缓存的频率设置，如果有较高并发建议设置大些，避免反复销毁创建连接，反之设置小些
     */
    private int maxIdle=50;
    /**
     * 获取连接最大等待时间，建议不要设置太长时间
     */
    private long maxWaitMillis=3000;
    /**
     * 最大连接数
     */
    private int maxTotal=500;

    public RedisClient(){}


    public RedisClient(String host, int port, String auth){
        this.host = host;
        this.port = port;
        this.auth = auth;

        try{
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(maxTotal);
            config.setMaxIdle(maxIdle);
            config.setMaxWaitMillis(maxWaitMillis);
            if(StrUtil.isBlank(auth)){
                jedisPool = new JedisPool(config, host, port, timeOut);
            }else{
                jedisPool = new JedisPool(config, host, port, timeOut, auth);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static RedisClient getInstance(String host, int port, String auth){
        if (null == instance){
            synchronized (RedisClient.class){
                if (null == instance){
                    instance = new RedisClient(host, port, auth);
                }
            }
        }
        return instance;
    }

    /**
     * 处理日志信息
     *
     * @param message
     */
    @Override
    public void handlerMessage(String message) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.lpush(Constants.REDIS_LOG_KEY, message);
        }finally {
            if (null != jedis){
                jedis.close();
            }
        }
    }

    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getAuth() {
        return auth;
    }

    public void setAuth(String auth) {
        this.auth = auth;
    }
}
